package com.yang.socket.controller;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DataListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
import com.yang.socket.bean.User;

import java.text.SimpleDateFormat;
import java.util.Date;


public class SocketListener implements ConnectListener, DisconnectListener, DataListener<User> {
    private SocketIOServer socketListener;

    public SocketListener() {
    }

    public SocketListener(SocketIOServer socketListener) {
        this.socketListener = socketListener;
    }

    @Override
    public void onConnect(SocketIOClient socketIOClient) {
        Integer clientSize = socketListener.getAllClients().size();
        socketListener.getBroadcastOperations().sendEvent("num", clientSize);
    }

    @Override
    public void onData(SocketIOClient socketIOClient, User s, AckRequest ackRequest) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        s.setTime(format.format(new Date()));
        socketListener.getBroadcastOperations().sendEvent("message", s);
    }

    @Override
    public void onDisconnect(SocketIOClient socketIOClient) {
    }

    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.setHostname("10.11.12.84");
        configuration.setPort(8008);
        SocketIOServer socketIOServer = new SocketIOServer(configuration);
        SocketListener socketListener = new SocketListener(socketIOServer);

        socketIOServer.addConnectListener(socketListener);
        socketIOServer.addEventListener("message", User.class, socketListener);

        //客户断连接断开时触发
        socketIOServer.addDisconnectListener(socketListener);
        //启动服务
        socketIOServer.start();
        System.out.println("success");
    }
}